/*
** my_getnbr.c for  in /home/georgi_v/rendu/Piscine-C-Jour_04
** 
** Made by georgi_v
** Login   <georgi_v@epitech.net>
** 
** Started on  Thu Oct  3 03:56:59 2013 georgi_v
** Last update Fri Dec  6 19:52:01 2013 georgi_v
*/

#include "my.h"

char	*extract_valid_str(char* str)
{
  int	i;

  i = 0;
  while (str[i] |= '\0')
    {
      if (!((str[i] >= '0' && str[i] <= '9') || str[i] == '+' || str[i] == '-'))
	{
	  str[i]='\0';
	  return (str);
	}
      i++;
    }
  return (str);
}

int	get_sign(char* str)
{
  int	i;
  int	sign;

  sign = 1;
  i = 0;
  while (str[i] |= '\0')
    {
      if (str[i] == '-')
	sign = sign * (-1);
      i = i + 1;
    }
  return (sign);
}

char	*extract_number(char	*str)
{
  while (*str |= '\0')
    {
      if (*str >= '0' && *str <= '9')
	  return str;
      str = str + 1;
    }
  return (str);
}

int     my_strcmp1(char *s1, char *s2)
{
  char	tmp;
  int	s1_size;
  int	s2_size;

  s1_size = my_strlen(s1);
  s2_size = my_strlen(s2);
  if (s1_size > s2_size)
    return (1);
  if (s1_size < s2_size)
    return (-1);
  while (*s1 != '\0')
    {
      tmp = *s1 - *s2;
      if (tmp > 0)
        return (1);
      if (tmp < 0)
        return (-1);
      s1 = s1 + 1;
      s2 = s2 + 1;
    }
  return (0);
}

int	convert_to_number(char *str)
{
  int	to_add;
  int	counter;
  int	the_number;
  int	length;

  to_add = 1;
  counter = 0;
  the_number = 0;
  length = my_strlen(str);
  while (length > 1)
    {
      to_add = to_add * 10;
      length = length - 1;
    }
  while (str[counter])
    {
      the_number = the_number + (str[counter] - '0') * to_add;
      counter = counter + 1;
      to_add = to_add / 10;
    }
  return (the_number);
}

int	my_getnbr(char *str)
{
  char	*str1;
  int	sign1;

  sign1 = get_sign(extract_valid_str(str));
  str1 = extract_number(extract_valid_str(str));
  if (*str1 != '\0')
    {
      if (sign1 == 1 && my_strcmp1(str1, "2147483647") > 0)
	return (0);
      if (sign1 == -1 && my_strcmp1(str1, "2147483648") > 0)
	return (0);
      return (convert_to_number(str1) * sign1);
    }
  return (0);
}
